package com.chiao.service.core;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.chiao.entity.Member;

import freemarker.template.Template;


@Service
public class MailService {

	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	@Autowired
	private TaskExecutor taskExecutor;
	
	/**
	 * 以html格式发送邮件
	 * @param from
	 * @param to
	 * @param sub
	 * @param text
	 * @throws MessagingException
	 */
	private void sendMsg(String from ,String to,String sub,String text) throws MessagingException{
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
		helper.setFrom(from);
		helper.setTo(to);
		helper.setSubject(sub);
		helper.setText(text,true);
		addSendMailTask(message);
	}
	
	// 增加邮件发送任务
	public void addSendMailTask(final MimeMessage mimeMessage) {
		try {
			taskExecutor.execute(new Runnable() {
				public void run() {
					mailSender.send(mimeMessage);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 会员注册后，发送注册邮件
	 * @param sub
	 * @param m
	 * @throws MessagingException
	 */
	public void sendRegMsg(Member m) throws MessagingException{
		String htmlText=getMailText(m.getName());
		String from = "zhangyinyou@126.com";
		sendMsg(from , m.getEmail(), "xx网-注册成功", htmlText);
	}
	
	
	
	/**
	 * 通过注册的模版生成text
	 * @param username
	 * @return
	 */
	private String getMailText(String username) {
		String htmlText = "";
		try {
			Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl");
			Map map = new HashMap();
			map.put("username", username);
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return htmlText;
	}
	
}
